package com.taoge.p4.sys;

import com.taoge.p4.common.annotation.NotSign;
import com.taoge.p4.common.constants.GlobalConstants;
import com.taoge.p4.common.entity.ResponseData;
import com.taoge.p4.common.entity.SysUser;
import com.taoge.p4.common.exception.ParamException;
import com.taoge.p4.common.params.LoginParam;
import com.taoge.p4.common.params.SysRegisterParam;
import com.taoge.p4.common.service.SysUserService;
import com.taoge.p4.common.utils.CookieUtil;
import com.taoge.p4.common.utils.TokenUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@Validated
@RequestMapping("/sys/user")
public class SysUserController {
    private final SysUserService sysUserService;

    private final HttpServletResponse response;

    @PostMapping("/register")
    public ResponseData<?> register(@Valid @RequestBody SysRegisterParam param) {
        if (!param.getPassword().equals(param.getConfirmPassword())) {
            throw new ParamException("两次密码不一致");
        }
        sysUserService.register(param);
        return ResponseData.success();
    }

    @NotSign
    @PostMapping("/login")
    public ResponseData<?> login(@Valid @RequestBody LoginParam param) {
        SysUser user =  sysUserService.login(param);
        String token = TokenUtil.generateToken(user.getId());
        CookieUtil.setCookie(GlobalConstants.SYS_TOKEN, token,response);
        return ResponseData.success();
    }
}
